package org.ricks.net;

import org.ricks.ioc.RicksContext;
import org.ricks.net.action.*;
import org.ricks.net.action.context.head.DefHeadMeta;
import org.ricks.net.action.context.FlowContext;
import org.ricks.net.action.context.session.TcpSessionAdapter;
import org.ricks.net.action.parser.ProtocolParserEnum;
import org.ricks.net.extension.protocol.ByteArrayProtocol;
import org.ricks.net.transport.AioQuickClient;
import org.ricks.net.transport.AioQuickServer;
import org.ricks.net.transport.AioSession;

import java.nio.ByteBuffer;

public class StringDemo {

    public static void main(String[] args) throws Exception {

        RicksContext.me().init();
        //启动服务端
        MessageProcessor<byte[]> serverProcessor = (session, msg) -> {
            ByteBuffer byteBuffer = ByteBuffer.wrap(msg);
            short cmd = byteBuffer.getShort();
            byte[] bytes = new byte[byteBuffer.remaining()];
            byteBuffer.get(bytes);
            ActionBus.handlerAction(session.hashCode(),
                    new FlowContext<>(new TcpSessionAdapter(session, ProtocolParserEnum.STRING.getParser()),new DefHeadMeta(cmd),bytes,
                    ProtocolParserEnum.STRING.getParser()));
        };
        AioQuickServer server = new AioQuickServer(8888, new ByteArrayProtocol(), serverProcessor);
        server.start();

        //启动客户端
        MessageProcessor<byte[]> clientProcessor = (session, msg) -> {
            System.out.println("receive data from server：" + new String(msg));
        };
        AioQuickClient aioQuickClient = new AioQuickClient("localhost", 8888, new ByteArrayProtocol(), clientProcessor);
        AioSession session = aioQuickClient.start();
        byte[] bytes = "smart-socket - ricks is god".getBytes();
        //encode
        session.writeBuffer().writeInt(bytes.length + 2);
        session.writeBuffer().writeShort((short) 1);
        session.writeBuffer().write(bytes);
        //flush data
        session.writeBuffer().flush();

        //shutdown
        Thread.sleep(10000);
        aioQuickClient.shutdownNow();
        server.shutdown();
    }
}
